package com.foreveross.chameleon.mdm;

import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.provider.Settings;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

/**
 * project: android_api_learn
 * ate: 14-10-8
 * author: wzq
 * description: TODO
 */
public class MdmDeviceInfoUtils {

    /**
     * 电池信息
     *
     * @return percent of battery level like 70%
     */
    public static String getBatteryInfo(Context context) {
        IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent batteryStatus = context.registerReceiver(null, ifilter);

    /*
        // Are we charging / charged?
        int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
        boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                status == BatteryManager.BATTERY_STATUS_FULL;

        // How are we charging?
        int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
        boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
    */


        int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
        float batteryPct = level / (float) scale;

        return (batteryPct * 100) + " %";
    }


    public static boolean externalMemoryAvailable() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }

    /**
     * 获取内部存储(非外置SD卡)可用容量
     *
     * @return 如 2003M
     */
    public static String getAvailableInternalMemorySize() {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        return formatSize(availableBlocks * blockSize);
    }

    /**
     * 获取内部存储(非外置SD卡)总容量
     *
     * @return 如 2003M
     */
    public static String getTotalInternalMemorySize() {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long totalBlocks = stat.getBlockCount();
        return formatSize(totalBlocks * blockSize);
    }

    /**
     * 获取内部存储(外置SD卡)可用容量
     *
     * @return 如 2003M
     */
    public static String getAvailableExternalMemorySize() {
        if (externalMemoryAvailable()) {
            File path = Environment.getExternalStorageDirectory();
            StatFs stat = new StatFs(path.getPath());
            long blockSize = stat.getBlockSize();
            long availableBlocks = stat.getAvailableBlocks();
            return formatSize(availableBlocks * blockSize);
        } else {
            return "no external memory";
        }
    }

    /**
     * 获取内部存储(外置SD卡)总容量
     *
     * @return 如 2003MB / 100KB
     */
    public static String getTotalExternalMemorySize() {
        if (externalMemoryAvailable()) {
            File path = Environment.getExternalStorageDirectory();
            StatFs stat = new StatFs(path.getPath());
            long blockSize = stat.getBlockSize();
            long totalBlocks = stat.getBlockCount();
            return formatSize(totalBlocks * blockSize);
        } else {
            return "no external memory";
        }
    }

    private static String formatSize(long size) {
        String suffix = null;

        if (size >= 1024) {
            suffix = "KB";
            size /= 1024;
            if (size >= 1024) {
                suffix = "MB";
                size /= 1024;
            }
        }

        StringBuilder resultBuffer = new StringBuilder(Long.toString(size));

        int commaOffset = resultBuffer.length() - 3;
        while (commaOffset > 0) {
            resultBuffer.insert(commaOffset, ',');
            commaOffset -= 3;
        }

        if (suffix != null) resultBuffer.append(suffix);
        return resultBuffer.toString();
    }


    /** wifi mac地址 */
    public static String getWifiMac(Context context) {
        WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = manager.getConnectionInfo();
        String address = info.getMacAddress();
        if (address == null) {
            address = "wifi disabled";
        }
        return address;
    }

    public static String getBluetoothMac() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        String address = bluetoothAdapter.getAddress();
        if (address == null) {
            address = "BlueTooth disable";
        }
        return address;
    }

    public static String getDeviceId(Context context) {
        String androidid = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        return androidid;
    }

    /**
     * @return true of false
     */
    public static boolean isRoot() {
        return findBinary("su");
    }

    private static boolean findBinary(String binaryName) {
        boolean found = false;
        if (!found) {
            String[] places = {"/sbin/",
                    "/system/bin/",
                    "/system/xbin/",
                    "/data/local/xbin/",
                    "/data/local/bin/",
                    "/system/sd/xbin/",
                    "/system/bin/failsafe/",
                    "/data/local/"};
            for (String where : places) {
                if (new File(where + binaryName).exists()) {
                    found = true;
                    System.out.println("found bin" + where + binaryName);
                    break;
                }
            }
        }
        return found;
    }

    public static String getDeviceInfo(Context ctx) throws JSONException {
        JSONObject json = new JSONObject();
        json.put("result", "true");
        json.put("desc", "暂无描述");

        JSONArray jsonArray = new JSONArray();
        JSONObject listItem = new JSONObject();

        // iphone特有 android没有的字段
        listItem.put("AvailableDeviceCapacity", "");//兼容iphone
        listItem.put("DeviceCapacity", "");//兼容iphone
        listItem.put("IsActivationLockEnabled", "");//兼容iphone
        listItem.put("IsCloudBackupEnabled", "");//兼容iphone
        listItem.put("IsDeviceLocatorServiceEnabled", "");//兼容iphone
        listItem.put("IsDoNotDisturbInEffect", "");//兼容iphone
        listItem.put("UDID", "");//TODO
        listItem.put("iTunesStoreAccountIsActive", "");


        // 都有的字段
        listItem.put("BatteryLevel", getBatteryInfo(ctx));// 电池
        listItem.put("BluetoothMAC", getBluetoothMac());// BluetoothMAC
        listItem.put("BuildVersion", Build.VERSION.RELEASE);
        listItem.put("DeviceName", Build.USER);
        listItem.put("EASDeviceIdentifier", getDeviceId(ctx));
        listItem.put("IsSupervised", isRoot());
        listItem.put("Model", Build.MODEL);
        listItem.put("ProductName", Build.PRODUCT);
        listItem.put("SerialNumber", Build.SERIAL);
        listItem.put("WiFiMAC", getWifiMac(ctx));

        // android 特有的字段
        listItem.put("AvailableInternalMemorySize", getAvailableInternalMemorySize());
        listItem.put("AvailableExternalMemorySize", getAvailableExternalMemorySize());
        listItem.put("TotalInternalMemorySize", getTotalInternalMemorySize());
        listItem.put("TotalExternalMemorySize", getTotalExternalMemorySize());

        //
        jsonArray.put(listItem);
        json.put("list",jsonArray);

        // toString
        return json.toString();
    }
}
